import axios from 'axios'
import {Message} from 'element-ui'
import getServerTime from './getServerTime'

const timeout = process.env.OFFLINE ? 10 : undefined

const service = axios.create({
  // 设置axios 请求过期时间
  timeout: timeout,
  // 设置axios 请求前置路径
  baseURL: process.env.SERVER_URL,
  // baseURL: 'http://192.168.2.206:8080/',
  // baseURL: 'http://192.168.2.210:8080/',
  // baseURL: 'http://120.55.115.151:8090/app/mock/1/',
  // 设置axios 允许跨域请求
  withCredentials: true
})
// 设置axios 请求拦截
service.interceptors.request.use(
  config => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config['crossDomain'] = true
    return config
  },
  error => {
    Promise.reject(error)
  }
)
service.interceptors.response.use(
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    getServerTime(response)
    const res = response.data
    if (response.config.responseType === 'blob') {
      if (res.type === 'application/json') {
        let reader = new FileReader();
        reader.onload = e => {
          let data = JSON.parse(e.target.result)
          if (data.code !== 200) {
            Message({
              message: data.message,
              type: 'error',
              duration: 2000,
              center: true
            })
          }
        }
        reader.readAsText(res, ['utf-8']);
        let error = new Error(res)
        return Promise.reject(error)
      } else {
        return response.data
      }
    } else if (!res || res.code !== 200) {
      let msg = '接口参数错误'
      if (res && res.message) {
        msg = res.message
      }
      Message({
        message: msg,
        type: 'error',
        duration: 2000,
        center: true
      })
      let error = new Error(res)
      return Promise.reject(error)
    } else {
      return response.data
    }
  },
  error => {
    if (!axios.isCancel(error)) {
      console.dir(error)
      let msg = ''
      if (error.request.status === 302) {
        msg = '请先登录'
      } else if (error.request && error.request.data) {
        msg = error.request.data.message
      } else if (error.request.status === 403) {
        msg = '可能是没有模块访问权限或接口地址错误'
      } else if (error.request.status === 404) {
        msg = '接口地址错误'
      } else {
        msg = 'Something Happened'
      }
      Message({
        message: msg,
        type: 'error',
        duration: 3 * 1000,
        center: true,
        onClose: () => {
          if (error.request.status === 302 && !process.env.OFFLINE) {
            window.location = process.env.SERVER_URL
          }
        }
      })
    }
    return Promise.reject(error)
  }
)

function fetch(obj) {
  if (!obj.url) {
    let err = new Error('请传入请求路径')
    return Promise.reject(err)
  } else if (!obj.method) {
    let err = new Error('请传入请求方式')
    return Promise.reject(err)
  }
  let servicObj = {
    method: obj.method,
    url: obj.url,
    headers: obj.headers || {},
    params: obj.params || {}
  }
  if (obj.onUploadProgress) {
    servicObj.onUploadProgress = obj.onUploadProgress
  }
  if (obj.responseType) {
    servicObj.responseType = obj.responseType
  }
  if (obj.cancelToken) {
    servicObj.cancelToken = obj.cancelToken
  }
  if (obj.method.toLocaleLowerCase() === 'get') {
    servicObj.param = obj.data || {}
  } else if (obj.method.toLocaleLowerCase() === 'post') {
    servicObj.data = obj.data || {}
  }
  return service(servicObj)
}

export default fetch
